package com.googlecode.tidej.shared.idl;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.tidej.shared.model.Library;
import com.googlecode.tidej.shared.model.Model;
import com.googlecode.tidej.shared.model.Library.DocumentationLinkType;

public class IdlLoader {
  static class LibraryInfo {
    String name; 
    String idlUrl;
    String docUrl;
    Library.DocumentationLinkType docLinkType;
    
    LibraryInfo(String name, String idlUrl, String docUrl, Library.DocumentationLinkType docLinkType) {
      this.name = name;
      this.idlUrl = idlUrl;
      this.docUrl = docUrl;
      this.docLinkType = docLinkType;
    }
  }
  
  Model model;
  AsyncCallback<Void> callback;
  int index = 0;
  static final LibraryInfo[] IDL_FILES = {
    new LibraryInfo("ECMAScript", "idl/ecmascript.idl", 
        "http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf",
        DocumentationLinkType.NONE),
    new LibraryInfo("DOM Level 3 Core", "idl/dom.idl",
        "http://www.w3.org/TR/DOM-Level-3-Core/",
        DocumentationLinkType.NONE),
    new LibraryInfo("Typed Array 1.0", "idl/typedarray.idl",
        "https://www.khronos.org/registry/typedarray/specs/1.0/",
        DocumentationLinkType.NONE),
    new LibraryInfo("Canvas 2D", "idl/canvas2d.idl", 
        "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html",
        DocumentationLinkType.WHATWG),
 /*   new LibraryInfo("WebGL 1.0", "idl/webgl.idl",
        "https://www.khronos.org/registry/webgl/specs/1.0/",
        DocumentationLinkType.NONE) */
  };
  
  public IdlLoader(Model model, AsyncCallback<Void> callback) {
    this.model = model;
    this.callback = callback;
  }
  
  public void run() {
    if (index == IDL_FILES.length) {
      callback.onSuccess(null);
      return;
    } 
    final LibraryInfo info = IDL_FILES[index++];
    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, info.idlUrl);
    rb.setCallback(new RequestCallback() {
      @Override
      public void onResponseReceived(Request request, Response response) {
        try {
          Library lib = new Library(info.name, true);
          lib.setDocumentationLink(info.docUrl, info.docLinkType);
          new IdlParser(model, lib, response.getText()).parse();
          model.addLibrary(lib);
          run();          
        } catch(Exception e) {
          callback.onFailure(e);
        }
     }

      @Override
      public void onError(Request request, Throwable exception) {
        callback.onFailure(exception);
      }});
    
    try {
      rb.send();
    } catch(RequestException e) {
      callback.onFailure(e);
    }
  }
  
}
